<template>
  <div class="role-management">
    <el-card>
      <!-- 搜索区域 -->
      <div class="search-area mb-20">
        <el-form :model="searchForm" inline>
          <el-form-item label="角色名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入角色名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 操作按钮 -->
      <div class="action-area mb-20">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增角色
        </el-button>
      </div>

      <!-- 表格 -->
      <el-table :data="tableData" v-loading="loading">
        <el-table-column prop="id" label="ID" width="180" />
        <el-table-column prop="name" label="角色名称" />
        <el-table-column prop="state" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.state === 0 ? 'success' : 'danger'">
              {{ row.state === 0 ? "启用" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="380" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>

            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-area mt-20">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 角色表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色权限" prop="permissions">
          <el-tree
            ref="treeRef"
            :data="menuTree"
            :props="treeProps"
            show-checkbox
            node-key="id"
            :default-checked-keys="checkedPermissions"
            @check="handlePermissionCheck"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="handleSubmit"
          :loading="submitLoading"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules,
} from "element-plus";
import {
  getRoleList,
  getMenuList,
  createRole,
  getRolePermissions,
  updateRole,
  deleteRole,
} from "@/api/system";
import type { Role, Menu, MenuListParams } from "@/api/types";

// 搜索表单
const searchForm = reactive({
  name: "",
});

// 表格数据
const tableData = ref<Role[]>([]);
const loading = ref(false);

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0,
});

// 加载数据
const loadData = async () => {
  try {
    loading.value = true;
    const params = {
      page: pagination.page,
      size: pagination.size,
      name: searchForm.name || undefined,
    };

    const response = await getRoleList(params);
    tableData.value = response.data.data || [];
    pagination.total = response.data.total || 0;
  } catch (error) {
    console.error("加载角色列表失败:", error);
    ElMessage.error("加载角色列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.page = 1;
  loadData();
};

// 重置
const handleReset = () => {
  searchForm.name = "";
  pagination.page = 1;
  loadData();
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size;
  pagination.page = 1;
  loadData();
};

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.page = page;
  loadData();
};

// 对话框
const dialogVisible = ref(false);
const dialogTitle = computed(() => (formData.id ? "编辑角色" : "新增角色"));
const submitLoading = ref(false);

// 表单
const formRef = ref<FormInstance>();
const formData = reactive({
  id: null as number | null,
  name: "",
  permissions: [],
});

const formRules: FormRules = {
  name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
};

// 权限相关
const treeRef = ref();
const checkedPermissions = ref<number[]>([]);

const treeProps = {
  children: "children",
  label: "name",
};

// 获取权限菜单数据
const menuTree = ref<Menu[]>([]);
const loadMenuTree = async () => {
  const params: MenuListParams = {
    page: 1,
    size: 50,
    type: 0,
  };
  try {
    const response = await getMenuList(params);
    console.log(response);

    // 构建菜单树结构
    const menuList = response.data.data || [];
    const menuMap = new Map<number, Menu & { children?: Menu[] }>();
    const rootMenus: (Menu & { children?: Menu[] })[] = [];

    // 第一步：创建所有菜单项的映射，并初始化children属性
    menuList.forEach((menu) => {
      menuMap.set(menu.id, { ...menu, children: [] });
    });

    // 第二步：构建父子关系
    menuList.forEach((menu) => {
      const menuItem = menuMap.get(menu.id)!;

      if (menu.parentId === 0 || !menuMap.has(menu.parentId)) {
        // 根菜单（parentId为0或找不到父菜单）
        rootMenus.push(menuItem);
      } else {
        // 子菜单，添加到父菜单的children中
        const parentMenu = menuMap.get(menu.parentId)!;
        parentMenu.children!.push(menuItem);
      }
    });

    // 清理空的children数组
    const cleanEmptyChildren = (menus: (Menu & { children?: Menu[] })[]) => {
      menus.forEach((menu) => {
        if (menu.children && menu.children.length === 0) {
          delete menu.children;
        } else if (menu.children) {
          cleanEmptyChildren(menu.children);
        }
      });
    };

    cleanEmptyChildren(rootMenus);
    menuTree.value = rootMenus;
    console.log("构建后的菜单树:", menuTree.value);
  } catch (error) {
    console.error("加载菜单列表失败:", error);
    ElMessage.error("加载菜单列表失败");
  }
};
loadMenuTree();

// 新增
const handleAdd = () => {
  // 先重置表单
  resetForm();
  // 然后打开弹窗
  dialogVisible.value = true;
};

// 编辑
const handleEdit = (row: any) => {
  checkedPermissions.value = [];
  Object.assign(formData, { ...row });
  try {
    getRolePermissions({ id: row.id }).then((res: any) => {
      checkedPermissions.value = res.data.data;
      formData.permissions = res.data.data;
      if(res.code===0){
        dialogVisible.value = true;
      }
    });
  } catch (error) {
    console.error("加载角色权限失败:", error);
    ElMessage.error("加载角色权限失败");
  }
};

// 删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除角色"${row.name}"吗？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    deleteRole({ id: row.id })
      .then((_res) => {
        ElMessage.success("删除成功");
        // 重新加载数据
        loadData();
      })
      .catch((err) => {
        console.log("err", err);
      });
  } catch {
    // 用户取消
  }
};

// 权限选择变化
const handlePermissionCheck = (_data: any, checked: any) => {
  formData.permissions = checked.checkedKeys;
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
    submitLoading.value = true;

    if (formData.id) {
      // 编辑
      updateRole({
        id: formData.id,
        name: formData.name,
        permissions: formData.permissions,
      })
        .then((res) => {
          console.log("res", res);
          ElMessage.success("编辑成功");
          // 重新加载数据
          loadData();
        })
        .catch((err) => {
          console.log("err", err);
        });
    } else {
      // 新增
      await createRole(formData);
      ElMessage.success("新增成功");
    }

    dialogVisible.value = false;
    // 重置表单数据
    resetForm();
    // 重新加载数据
    loadData();
  } catch (error) {
    console.error("提交失败:", error);
  } finally {
    submitLoading.value = false;
  }
};

// 对话框关闭
const handleDialogClose = () => {
  checkedPermissions.value = [];
  // 确保树组件也清空选中状态
  setTimeout(() => {
    if (treeRef.value) {
      treeRef.value.setCheckedKeys([]);
    }
  }, 0);
  resetForm();
};

// 重置表单
const resetForm = () => {
  // 先重置表单字段验证状态
  formRef.value?.resetFields();
  
  // 然后重置表单数据
  formData.id = null;
  formData.name = "";
  formData.permissions = [];
  
  // 重置权限树选中状态
  checkedPermissions.value = [];
  setTimeout(() => {
    if (treeRef.value) {
      treeRef.value.setCheckedKeys([]);
    }
  }, 0);
};

onMounted(() => {
  loadData();
});
</script>

<style scoped>
.role-management {
  padding: 0;
}

.action-area {
  margin-bottom: 20px;
}
</style>
